"use client"

import { useState, useEffect } from "react"
import { Button } from "@/components/ui/button"
import { ArrowLeft, Play, Pause, Square, Timer } from "lucide-react"

interface TrainingPageProps {
  onBack: () => void
}

export function TrainingPage({ onBack }: TrainingPageProps) {
  const [isTraining, setIsTraining] = useState(false)
  const [currentRound, setCurrentRound] = useState(1)
  const [totalRounds] = useState(10)
  const [score, setScore] = useState(0)
  const [reactionTime, setReactionTime] = useState(245)
  const [timeLeft, setTimeLeft] = useState(300)
  const [activeLED, setActiveLED] = useState<number | null>(null)
  const [sequence, setSequence] = useState<number[]>([])
  const [userSequence, setUserSequence] = useState<number[]>([])
  const [gamePhase, setGamePhase] = useState<"waiting" | "showing" | "input" | "result">("waiting")

  const ledPositions = [
    { id: 1, x: 2, y: 1 },
    { id: 2, x: 3, y: 1 },
    { id: 3, x: 4, y: 2 },
    { id: 4, x: 4, y: 3 },
    { id: 5, x: 3, y: 4 },
    { id: 6, x: 2, y: 4 },
    { id: 7, x: 1, y: 3 },
    { id: 8, x: 1, y: 2 },
  ]

  useEffect(() => {
    let interval: NodeJS.Timeout
    if (isTraining && timeLeft > 0) {
      interval = setInterval(() => {
        setTimeLeft((prev) => prev - 1)
      }, 1000)
    }
    return () => clearInterval(interval)
  }, [isTraining, timeLeft])

  const startTraining = () => {
    setIsTraining(true)
    setGamePhase("showing")
    generateSequence()
  }

  const pauseTraining = () => {
    setIsTraining(false)
  }

  const stopTraining = () => {
    setIsTraining(false)
    setCurrentRound(1)
    setScore(0)
    setGamePhase("waiting")
    setActiveLED(null)
    setSequence([])
    setUserSequence([])
  }

  const generateSequence = () => {
    const newSequence = Array.from(
      { length: Math.min(3 + Math.floor(currentRound / 2), 8) },
      () => Math.floor(Math.random() * 8) + 1,
    )
    setSequence(newSequence)
    setUserSequence([])
    showSequence(newSequence)
  }

  const showSequence = async (seq: number[]) => {
    setGamePhase("showing")
    for (let i = 0; i < seq.length; i++) {
      await new Promise((resolve) => setTimeout(resolve, 500))
      setActiveLED(seq[i])
      await new Promise((resolve) => setTimeout(resolve, 800))
      setActiveLED(null)
      await new Promise((resolve) => setTimeout(resolve, 200))
    }
    setGamePhase("input")
  }

  const handleLEDClick = (ledId: number) => {
    if (gamePhase !== "input") return

    const newUserSequence = [...userSequence, ledId]
    setUserSequence(newUserSequence)

    if (newUserSequence[newUserSequence.length - 1] !== sequence[newUserSequence.length - 1]) {
      setGamePhase("result")
      setTimeout(() => nextRound(), 1500)
      return
    }

    if (newUserSequence.length === sequence.length) {
      setScore((prev) => prev + 10 * currentRound)
      setGamePhase("result")
      setTimeout(() => nextRound(), 1500)
    }
  }

  const nextRound = () => {
    if (currentRound < totalRounds) {
      setCurrentRound((prev) => prev + 1)
      generateSequence()
    } else {
      stopTraining()
    }
  }

  const formatTime = (seconds: number) => {
    const mins = Math.floor(seconds / 60)
    const secs = seconds % 60
    return `${mins}:${secs.toString().padStart(2, "0")}`
  }

  return (
    <div className="min-h-screen bg-white p-8">
      <div className="max-w-7xl mx-auto">
        {/* Header */}
        <div className="border-b border-gray-200 pb-6 mb-12">
          <div className="flex items-center justify-between">
            <div className="flex items-center space-x-4">
              <Button
                onClick={onBack}
                className="bg-transparent hover:bg-gray-100 text-black border border-gray-200 rounded-none h-8 px-4"
              >
                <ArrowLeft className="w-4 h-4 mr-2" />
                返回
              </Button>
              <span className="text-sm font-medium">SEQUENCE TRAINING</span>
            </div>
            <div className="flex items-center space-x-6 text-sm">
              <span>
                第 {currentRound}/{totalRounds} 轮
              </span>
              <span>
                <Timer className="w-4 h-4 inline mr-1" />
                {formatTime(timeLeft)}
              </span>
              <div className="flex items-center space-x-2">
                {!isTraining ? (
                  <Button
                    onClick={startTraining}
                    className="bg-green-500 hover:bg-green-600 text-white rounded-none h-8 px-4"
                  >
                    <Play className="w-4 h-4 mr-2" />
                    开始
                  </Button>
                ) : (
                  <>
                    <Button
                      onClick={pauseTraining}
                      className="bg-transparent hover:bg-gray-100 text-black border border-gray-200 rounded-none h-8 px-4"
                    >
                      <Pause className="w-4 h-4" />
                    </Button>
                    <Button
                      onClick={stopTraining}
                      className="bg-red-500 hover:bg-red-600 text-white rounded-none h-8 px-4"
                    >
                      <Square className="w-4 h-4" />
                    </Button>
                  </>
                )}
              </div>
            </div>
          </div>
        </div>

        {/* Main Content */}
        <div className="grid grid-cols-12 gap-8">
          {/* Left Stats */}
          <div className="col-span-3 border-r border-gray-200 pr-8">
            <div className="space-y-6">
              <div className="border border-gray-200 p-6">
                <div className="text-3xl font-bold text-black mb-2">{score}</div>
                <div className="text-sm text-gray-600">总分</div>
              </div>
              <div className="border border-gray-200 p-6">
                <div className="text-3xl font-bold text-black mb-2">{reactionTime}</div>
                <div className="text-sm text-gray-600">反应时间 (ms)</div>
              </div>
              <div className="border border-gray-200 p-6">
                <div className="text-3xl font-bold text-black mb-2">
                  {Math.round((score / (currentRound * 10)) * 100) || 0}%
                </div>
                <div className="text-sm text-gray-600">准确率</div>
              </div>
            </div>
          </div>

          {/* Training Area */}
          <div className="col-span-6">
            <div className="mb-8">
              <h1 className="text-4xl font-bold text-black mb-4 tracking-tight">
                SEQUENCE_
                <br />
                MEMORY
              </h1>
              <p className="text-gray-600">
                {gamePhase === "waiting" && "点击开始按钮开始训练"}
                {gamePhase === "showing" && "请记住LED亮起的顺序"}
                {gamePhase === "input" && "按照刚才的顺序点击LED"}
                {gamePhase === "result" && (userSequence.length === sequence.length ? "正确！" : "错误，继续加油！")}
              </p>
            </div>

            {/* LED Grid */}
            <div className="border border-gray-200 p-12">
              <div className="grid grid-cols-5 gap-4 max-w-md mx-auto">
                {Array.from({ length: 25 }, (_, index) => {
                  const row = Math.floor(index / 5) + 1
                  const col = (index % 5) + 1
                  const led = ledPositions.find((l) => l.x === col && l.y === row)

                  if (led) {
                    return (
                      <button
                        key={led.id}
                        onClick={() => handleLEDClick(led.id)}
                        disabled={gamePhase !== "input"}
                        className={`w-12 h-12 border-2 transition-all duration-300 ${
                          activeLED === led.id
                            ? "bg-orange-500 border-orange-500"
                            : "bg-white border-gray-300 hover:border-gray-400"
                        } ${gamePhase === "input" ? "cursor-pointer" : "cursor-not-allowed"}`}
                      >
                        <span className="text-sm font-bold">{led.id}</span>
                      </button>
                    )
                  } else {
                    return <div key={index} className="w-12 h-12 bg-gray-100"></div>
                  }
                })}
              </div>
            </div>

            {/* Sequence Display */}
            {sequence.length > 0 && (
              <div className="mt-8 text-center">
                <p className="text-sm text-gray-600 mb-4">
                  {gamePhase === "showing"
                    ? "正在显示序列..."
                    : gamePhase === "input"
                      ? `请输入 ${sequence.length} 个LED的顺序`
                      : "序列完成"}
                </p>
                <div className="flex justify-center space-x-2">
                  {sequence.map((ledId, index) => (
                    <div
                      key={index}
                      className={`w-8 h-8 border flex items-center justify-center text-sm font-bold ${
                        index < userSequence.length
                          ? userSequence[index] === ledId
                            ? "bg-green-500 border-green-500 text-white"
                            : "bg-red-500 border-red-500 text-white"
                          : "bg-white border-gray-300 text-gray-600"
                      }`}
                    >
                      {ledId}
                    </div>
                  ))}
                </div>
              </div>
            )}
          </div>

          {/* Right Progress */}
          <div className="col-span-3 pl-8 border-l border-gray-200">
            <div className="border border-gray-200 p-6">
              <div className="flex items-center justify-between mb-4">
                <span className="text-sm font-medium">训练进度</span>
                <div className="w-3 h-3 bg-orange-500 rounded-full"></div>
              </div>
              <div className="text-3xl font-bold text-black mb-2">
                {Math.round((currentRound / totalRounds) * 100)}%
              </div>
              <div className="text-sm text-gray-600 mb-4">完成度</div>
              <div className="bg-gray-100 h-2">
                <div
                  className="bg-orange-500 h-2 transition-all duration-500"
                  style={{ width: `${(currentRound / totalRounds) * 100}%` }}
                ></div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}
